import { useEffect, useState } from 'preact/hooks'
import { Account } from './types/account';
import { RecordCard } from './components/shared/RecordCard';
import { Record } from './types/record';
import { fetchAccounts } from './api/account';
import { fetchRecords } from './api/record';
import { FunctionContext } from './context/FC';

export function App() {
  const [accounts,setAccounts] = useState<Account[]>([])
  const [records,setRecords] = useState<Record[]>([])
  useEffect(()=>{
      const fetchData = async ()=>{
        await fetchAccounts(setAccounts)
        await fetchRecords(setRecords)
      }
      fetchData()
  },[])
  const getAccountName = (id:number)=>{
    const arr = accounts.filter(e=>e.id===id);
    if(arr.length>0){
      return arr[0].name;
    }
    console.log(`id:${id}没有对应账户，默认返回空白名称`)
    return ''
  }
  const getAccountTo = (idIn:number,idOut:number)=>{
    const nameIn = getAccountName(idIn);
    const nameOut = getAccountName(idOut);
    if(nameIn === ''){
      return nameOut
    }else if(nameOut===''){
      return nameIn;
    }
    return `${nameOut} > ${nameIn}`
  }
  return <div style={{display:'flex',flexDirection:'column',gap:'1vh',userSelect:'none'}}>
    <FunctionContext.Provider value={[getAccountName]} >
      {records && records.map(e=>(
        <RecordCard icon="测试" val11={e.flow_type} val13={e.amount} 
        val21={e.memos} 
        val22={`${getAccountTo(e.income_id,e.expense_id)}`}/>
      ))}
    </FunctionContext.Provider>
  </div>
}


/*
const AccountElement:React.FC<Account>=(props)=>{
  // useEffect(()=>{
  //   const fetchData = async ()=>{
  //     const array = await fetchAccounts();
  //     setAccounts(array)
  //   }
  //   fetchData()
  // },[])
  // return <>{accounts && accounts.map(e=><AccountElement key={e.id} {...e}/>)}</>
  return <div>
    <div>id:{props.id}</div>
    <div>账户名称：<input value={props.name} /></div>
    <div>初始金额：<input value={props.initial_amount} /></div>
    <div>备注信息：<input value={props.memos} /></div>
    <div>计入资产：<input type="checkbox" checked={props.exclude} /></div>
    
  </div>
}
  */